package com.colter.project.sample.dbcompare;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import static com.colter.project.sample.dbcompare.CompareConstant.*;

/**
 * @author liangchao03
 *         2017/10/24
 */
public class DataSource {
    private String driver;
    private String url;
    private String username;
    private String password;
    private String sql;

    private DataSource(String driver, String url, String username, String password, String sql) {
        this.driver = driver;
        this.url = url;
        this.username = username;
        this.password = password;
        this.sql = sql;
    }

    public static DataSource getDataSource1(){
        return new DataSource(Config.get(DB1_DRIVER),Config.get(DB1_URL),Config.get(DB1_USERNAME),Config.get(DB1_PASSWORD),Config.get(DB1_SQL));
    }

    public static DataSource getDataSource2(){
        return new DataSource(Config.get(DB2_DRIVER),Config.get(DB2_URL),Config.get(DB2_USERNAME),Config.get(DB2_PASSWORD),Config.get(DB2_SQL));
    }

    public List<List<Object>> getResult() {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            Class.forName(this.driver);
            conn = DriverManager.getConnection(this.url, this.username, this.password);
            ps = conn.prepareStatement(this.sql);
            rs = ps.executeQuery();
            List<List<Object>> result = new ArrayList<>();
            while (rs.next()) {
                List<Object> small = new ArrayList<>();
                int i = 1;
                while (i <= CompareConfig.colums) {
                    small.add(rs.getObject(i));
                    i++;
                }
                result.add(small);
            }
            return result;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return new ArrayList<>();
    }

}
